/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.deployment.servlet;

import br.com.deployment.entidade.arquivo.Anexo;
import br.com.deployment.exception.AnexoFoundException;
import br.com.deployment.exception.ejb.AnexoEjbException;
import br.com.deployment.message.Msg;
import br.com.deployment.servico.AnexoServico;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet(name = "imageUploadServlet",urlPatterns="/imageUploadServlet/*")
public class ImageUploadServlet extends HttpServlet {
    
    @EJB
    AnexoServico anexoServico;
 
    private static final long serialVersionUID = 201011231103L;
    
    public ImageUploadServlet() {
        super();
    }
 
    @Override
    protected void doGet(HttpServletRequest request,
         HttpServletResponse response) throws ServletException, IOException {
        
        String text = request.getParameter("anexo");
        Anexo anexo;
        OutputStream out  = response.getOutputStream();
        
        try {
            anexo = anexoServico.find(Integer.parseInt(text));
            response.setContentType(anexo.getTipo());
            response.getOutputStream().write(anexo.getArquivo());
        } catch (AnexoFoundException ex) {
            Msg.messagemError("Erro, Arquivo não encontrado ! ");
            Logger.getLogger(ImageUploadServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (AnexoEjbException ex) {
            Msg.messagemError("Erro no EJB ");
            Logger.getLogger(ImageUploadServlet.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (out != null) {
                out.close();
            }
        }       
    }
}